const std = @import("std");
const httpz = @import("httpz");
const teacher_service = @import("../services/teacher_service.zig");
const teacher_model = @import("../models/teacher_model.zig");

fn add(request: *httpz.Request, response: *httpz.Response) !void {
    const teacher = request.json(teacher_model.Teacher) catch {
        try response.json(.{ .result = false }, .{});
        return;
    };

    if (teacher == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }

    const res = try teacher_service.add(&teacher.?);
    try response.json(.{ .result = res }, .{});
}

fn query(request: *httpz.Request, response: *httpz.Response) !void {
    const teacher = request.json(teacher_model.Teacher) catch {
        try response.json(.{ .result = false }, .{});
        return;
    };

    if (teacher == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }

    try teacher_service.query(&teacher.?, response);
}

fn query_by_pk(request: *httpz.Request, response: *httpz.Response) !void {
    const form_data = try request.formData();
    const id_s = form_data.get("Id");
    if (id_s == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }
    const Id = try std.fmt.parseInt(i32, id_s.?, 10);
    const teacher = try teacher_service.query_by_pk(Id);
    try response.json(.{ .result = teacher }, .{});
}

fn update(request: *httpz.Request, response: *httpz.Response) !void {
    const teacher = request.json(teacher_model.Teacher) catch {
        try response.json(.{ .result = false }, .{});
        return;
    };

    if (teacher == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }

    const res = try teacher_service.update(&teacher.?);
    try response.json(.{ .result = res }, .{});
}

fn delete(request: *httpz.Request, response: *httpz.Response) !void {
    const form_data = try request.formData();
    const id_s = form_data.get("Id");
    if (id_s == null) {
        try response.json(.{ .result = false }, .{});
        return;
    }
    const Id = try std.fmt.parseInt(i32, id_s.?, 10);
    const res = try teacher_service.delete(Id);
    try response.json(.{ .result = res }, .{});
}

pub fn route(router: anytype) void {
    router.post("/teacher/add", add, .{});
    router.post("/teacher/query", query, .{});
    router.post("/teacher/query_by_pk", query_by_pk, .{});
    router.post("/teacher/update", update, .{});
    router.post("/teacher/delete", delete, .{});
}
